package fic.storefinder.server.updateservice.robe;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fic.storefinder.server.updateservice.ServiceInterface;
import fic.storefinder.server.updateservice.poi.GetPOIServlet;
import fic.storefinder.server.utils.ServerUtils;
import fic.storefinder.shared.StoreFinderServiceException;
import fic.storefinder.shared.StoreFinderServiceExceptionJson;
import fic.storefinder.shared.StoreFinderServiceExceptionXml;
import fic.storefinder.shared.utils.Constants;

@SuppressWarnings("serial")
public class GetRobeServlet extends HttpServlet {
	
	private Logger logger;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		PrintWriter out = resp.getWriter();
		try {
			logger = Logger.getLogger(GetRobeServlet.class.getName());
			// Check for parameters:
			String format = req.getParameter(Constants.REQUEST_PARAMETER_FORMAT);
			if (format == null) {
				throw new StoreFinderServiceException("\'" + Constants.REQUEST_PARAMETER_FORMAT + "\' parameter missing! \nPossible values: \'" + Constants.REQUEST_PARAMETER_VALUE_FORMAT_JSON + "\', \'" + Constants.REQUEST_PARAMETER_VALUE_FORMAT_XML + "\'",
						StoreFinderServiceException.ERROR_CODE_MISSING_PARAMETER);
			} else if (!format.equals(Constants.REQUEST_PARAMETER_VALUE_FORMAT_JSON) && !format.equals(Constants.REQUEST_PARAMETER_VALUE_FORMAT_XML)) {
				throw new StoreFinderServiceException("Invalid \'format\' parameter: \'" + format + "\'! \nPossible values: \'" + Constants.REQUEST_PARAMETER_VALUE_FORMAT_JSON + "\', \'" + Constants.REQUEST_PARAMETER_VALUE_FORMAT_XML + "\'", StoreFinderServiceException.ERROR_CODE_INVALID_PARAMETER);
			}

			String lastUpdateTimeStampString = req.getParameter(Constants.REQUEST_PARAMETER_LAST_UPDATE_TIMESTAMP);
			if (lastUpdateTimeStampString == null) {
				String errorMessage = "\'" + Constants.REQUEST_PARAMETER_LAST_UPDATE_TIMESTAMP + "\' parameter missing!";
				if (format.equals(Constants.REQUEST_PARAMETER_VALUE_FORMAT_JSON)) {
					throw new StoreFinderServiceExceptionJson(errorMessage, StoreFinderServiceException.ERROR_CODE_MISSING_PARAMETER);
				} else if (format.equals(Constants.REQUEST_PARAMETER_VALUE_FORMAT_XML)) {
					throw new StoreFinderServiceExceptionXml(errorMessage, StoreFinderServiceException.ERROR_CODE_MISSING_PARAMETER);
				}
			}
			Long lastUpdateTimeStamp = null;
			try {
				lastUpdateTimeStamp = new Long(lastUpdateTimeStampString);
			} catch (NumberFormatException e) {
				String errorMessage = "Invalid timestamp: \'" + lastUpdateTimeStampString + "\'";
				if (format.equals(Constants.REQUEST_PARAMETER_VALUE_FORMAT_JSON)) {
					throw new StoreFinderServiceExceptionJson(errorMessage, StoreFinderServiceException.ERROR_CODE_INVALID_PARAMETER);
				} else if (format.equals(Constants.REQUEST_PARAMETER_VALUE_FORMAT_XML)) {
					throw new StoreFinderServiceExceptionXml(errorMessage, StoreFinderServiceException.ERROR_CODE_INVALID_PARAMETER);
				}
			}
			
			//All parameter is valid, updatecheck:
			ServiceInterface getRobeService = null;
			if (format.equals(Constants.REQUEST_PARAMETER_VALUE_FORMAT_JSON)) {
				getRobeService = new GetRobeServiceJson();
			} else if (format.equals(Constants.REQUEST_PARAMETER_VALUE_FORMAT_XML)) {
				getRobeService = new GetRobeServiceXml();
			}
			HashMap<String, Object> parameters = new HashMap<String, Object>();
			parameters.put(Constants.REQUEST_PARAMETER_LAST_UPDATE_TIMESTAMP, lastUpdateTimeStamp);
			getRobeService.setParameters(parameters);
			
			String response = getRobeService.generateResponse();
			logger.info("Server response: " + response);
			out.println(response);

		} catch (StoreFinderServiceException e) {
			try {
				logger.warning("Server error: " + e.getMessage());
				if (e instanceof StoreFinderServiceExceptionJson || e instanceof StoreFinderServiceExceptionXml) {
					out.println(e.getFormattedMessage());
				} else {
					out.println("An error occurred during processing your request!");
					out.println("Error code: " + e.getErrorCode());
					out.print(ServerUtils.getStringFromStackTrace(e));
				}
			} catch (Exception e2) {
				out.println("An error occurred during processing your request!");
				out.println(ServerUtils.getStringFromStackTrace(e));
			}
			
			

		} catch (Exception e) {
			logger.warning("Server error: " + e.getMessage());
			out.println("An error occurred during processing your request!");
			out.println(ServerUtils.getStringFromStackTrace(e));

		} finally {
			out.flush();
		}

	}
}
